package com.hmdp.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hmdp.dto.Result;
import com.hmdp.entity.Shop;
import com.hmdp.mapper.ShopMapper;
import com.hmdp.service.IShopService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hmdp.utils.CacheClient;
import com.hmdp.utils.RedisConstants;
import com.hmdp.utils.RedisData;
import com.hmdp.utils.SystemConstants;
import org.springframework.data.geo.Distance;
import org.springframework.data.geo.GeoResult;
import org.springframework.data.geo.GeoResults;
import org.springframework.data.redis.connection.RedisGeoCommands;
import org.springframework.data.redis.core.RedisCommand;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.domain.geo.GeoReference;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.PathVariable;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 虎哥
 * @since 2021-12-22
 */
@Service
public class ShopServiceImpl extends ServiceImpl<ShopMapper, Shop> implements IShopService {
@Resource
private StringRedisTemplate stringRedisTemplate;
@Resource
private CacheClient cacheClient;
    private static final String LOCK_SHOP_KEY = "lock:shop:";
    private final ExecutorService executors= Executors.newFixedThreadPool(10);
    private Boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    private void unlock(String key){
        stringRedisTemplate.delete(key);
    }
    @Override
    public Result cacheById(Long id) {
        //互斥锁解决缓存穿透测试
        Shop shop = queryWithMutex(id);
        //测试缓存击穿工具类
//        Shop shop = cacheClient.queryWithPassThrough(RedisConstants.CACHE_SHOP_KEY,
//            id,Shop.class,this::getById,RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES);
//        Shop shop =cacheClient.queryWithExpire(RedisConstants.CACHE_SHOP_KEY,id,Shop.class,this::getById,RedisConstants.CACHE_SHOP_TTL,TimeUnit.MINUTES);
        if(shop==null){
            return Result.fail("店铺不存在");
        }
        return Result.ok(shop);
    }
    //利用互斥锁，解决缓存击穿的问题
    public Shop queryWithMutex( Long id) {
        String cacheKey = RedisConstants.CACHE_SHOP_KEY+ id;
        String jsonStr = stringRedisTemplate.opsForValue().get(cacheKey);
        if(!StrUtil.isBlank(jsonStr)){
            Shop shop = JSONUtil.toBean(jsonStr, Shop.class);
            return shop;
        }
        //因为如果redis和数据库中都没有缓存了空值，当再次查询时，遇到空字符串就会返回
        if(Objects.equals(jsonStr, "")){
            return null;
        }
        //redis中不存在查询数据库，然后保存到redis中

        //让一个线程进行缓存重建

        //获取互斥锁，失败就线程暂时关闭
        Shop shop = null;
        try {
            Boolean lock = tryLock(LOCK_SHOP_KEY + id);
            if(!lock){
                Thread.sleep(50);
                return queryWithMutex(id);
            }
            //互斥锁获取成功，进行缓存重建,但获取锁成功后要进行二次耗材查询redis，防止其他线程已经重建好了
            String str = stringRedisTemplate.opsForValue().get(cacheKey);
            if(!StrUtil.isBlank(str)){
                return JSONUtil.toBean(str, Shop.class);
            }
            shop = getById(id);
            if(shop==null){
                //数据库中不存在缓存空值
                stringRedisTemplate.opsForValue().set(cacheKey,"",RedisConstants.CACHE_NULL_TTL,TimeUnit.MINUTES);
                return null;
            }
            stringRedisTemplate.opsForValue().set(cacheKey, JSONUtil.toJsonStr(shop), 30, TimeUnit.MINUTES);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        } finally {
            unlock(LOCK_SHOP_KEY + id);
        }
        return shop;
    }

    //查询数据库并进行redis缓存的方法
    public void saveShop(Long id,Long expireTime) {
        String cacheKey = RedisConstants.CACHE_SHOP_KEY+ id;
        Shop shop = getById(id);
        RedisData redisData = new RedisData();
        redisData.setData(shop);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(expireTime));
        stringRedisTemplate.opsForValue().set(cacheKey, JSONUtil.toJsonStr(redisData));
    }
    @Override
    public Result updateCache(Shop shop) {
        if(shop.getId() == null){
            return Result.fail("店铺不存在！");
        }
        //先更新数据库
        updateById(shop);
        //再删除缓存
        stringRedisTemplate.delete(RedisConstants.CACHE_SHOP_KEY+shop.getId());
        return Result.ok();
    }

    @Override
    //获取附近商铺
    public Result queryShopByType(Integer typeId, Integer current, Double x, Double y) {
        if (x==null || y==null){
            // 根据类型分页查询
            Page<Shop> page =query()
                    .eq("type_id", typeId)
                    .page(new Page<>(current, SystemConstants.DEFAULT_PAGE_SIZE));
            // 返回数据
            return Result.ok(page.getRecords());
        }
        //获取分页参数
        int from=(current-1)*SystemConstants.DEFAULT_PAGE_SIZE;
        int end=current*SystemConstants.DEFAULT_PAGE_SIZE;
        //附近搜索
        GeoResults<RedisGeoCommands.GeoLocation<String>> results = stringRedisTemplate.opsForGeo().search(RedisConstants.SHOP_GEO_KEY + typeId,
                GeoReference.fromCoordinate(x, y),//圆心坐标
                new Distance(5000),//半径
                RedisGeoCommands.GeoSearchCommandArgs.newGeoSearchArgs().includeDistance().limit(end));
        if (results==null){
            return Result.ok(Collections.emptyList());
        }
        List<GeoResult<RedisGeoCommands.GeoLocation<String>>> list = results.getContent();
        //如果查到的数据条数小于等于要查询的条数的开始点，如一共九条数据，要查第11条即第三页
        if(list.size()<=from){
            return Result.ok(Collections.emptyList());
        }
        Map<String,Distance> map = new HashMap<>(list.size());
        List<Long> ids = new ArrayList<>(list.size());
        list.stream().skip(from).forEach(result->{
            String idStr = result.getContent().getName();//店铺id
            ids.add(Long.valueOf(idStr));
            Distance distance = result.getDistance();//距离
            map.put(idStr,distance);
        });
        //根据ids来查询店铺的信息
        String join = StrUtil.join(",", ids);
        List<Shop> shops = query().in("id", ids).last("ORDER BY FIELD(id," + join + ")").list();
        //封装并返回
        for (Shop shop : shops) {
            shop.setDistance(map.get(shop.getId().toString()).getValue());
        }
        return Result.ok(shops);
    }
}
